package com.qf.drbackend.filters;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qf.drbackend.pojos.R;
import com.qf.drbackend.utils.JwtUtils;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

public class LoginFilter extends UsernamePasswordAuthenticationFilter {

    private AuthenticationManager authenticationManager;

    //认证过程中，所有的核心操作都由这个AuthenticationManager管理器完成。
    public LoginFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
        this.authenticationManager = authenticationManager;
    }

    /**
     * 登录成功的回调方法
     *  jwt到底怎么说明 你是你。 jwt组成：header、payload、signitrue
     *      header： jwt预定义信息  -- 明文
     *      payload：自定义信息 （自定义信息不可以有敏感信息，比如用户的密码，密码加密盐值） -- 明文
     *      signitrue： 签名信息，【对header和payload】的明文信息通过我们【自定义的密钥加密】后得到的字符串
     *
     *  jwt ===>  header.payload.signitrue
     *
     * @param request
     * @param response
     * @param chain
     * @param authResult
     * @throws IOException
     * @throws ServletException
     */
    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
        //将用户的信息，以jwt形式组织后，响应到浏览器端
        User principal = (User) authResult.getPrincipal();

        //返回的是用户id
        String uid = principal.getUsername();

        //基于当前的uid信息返回一个token
        String token = JwtUtils.createToken(new HashMap(), uid);

        //将token响应会前台
        R r = R.success(token);

        String json = new ObjectMapper().writeValueAsString(r);

        response.getWriter().write(json);
    }

    /**
     * 登录失败的回调方法
     * @param request
     * @param response
     * @param failed
     * @throws IOException
     * @throws ServletException
     */
    @Override
    protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException {
        R r = R.error("用户名或密码错误");

        String json = new ObjectMapper().writeValueAsString(r);

        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(json);
    }
}
